package com.yanxu.base;

import com.utils.Const;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.rebalance.AllocateMessageQueueConsistentHash;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/3/31-2024
 * @Description: 这里用一句话描述这个类的作用
 */
public class BaseConsumer {
    public static void main(String[] args) throws Exception {
        //DefaultLitePullConsumer consumer=new DefaultLitePullConsumer("a-consumer");
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("a-consumer");

        //设置消费的模式。 默认情况下是集群消费。可以修改为 '广播消费'
        //consumer.setMessageModel(MessageModel.BROADCASTING);

        //设置 NameServer 的地址
        consumer.setNamesrvAddr(Const.NAME_SERVER_SINGLE);

        //从队列第一个消息开始进行消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        // 从指定的时间戳进行消费
        //consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_TIMESTAMP);
        //consumer.setConsumeTimestamp("20240402100326"); //年月日时分秒

        // 设置队列分配策略
        consumer.setAllocateMessageQueueStrategy(new AllocateMessageQueueConsistentHash());



        //订阅第一个主题下消息
        consumer.subscribe("topic-a","*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list) {
                    System.out.println(new String(messageExt.getBody()));
                    //consumer.setOffsetStore();
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        //订阅第二个注意下的消息
        consumer.subscribe("topic-b","*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list) {
                    System.out.println(new String(messageExt.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
        Thread.sleep(1000000000);
    }
}